<?php

namespace Common\Listener;

use common\Event\Notify;
use Common\Event\SendToMqtt;
use Common\Event\SendToTcp;
use Common\Event\SendToWebSocket;
use Common\Helpers\DebugHelper;
use Common\Mqtt\MqttServer;
use Common\Mqtt\Utility\MqttUtility;
use Hyperf\Context\ApplicationContext;
use Hyperf\Contract\ConfigInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Hyperf\WebSocketServer\Sender;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Simps\MQTT\Client;

#[Listener]
class NotifyListener implements ListenerInterface
{

    /**
     * @var Sender
     */
    #[Inject]
    protected Sender $sender;

    public function listen(): array
    {
        // 返回一个该监听器要监听的事件数组，可以同时监听多个事件
        return [
            Notify::class,
            SendToWebSocket::class,
            SendToTcp::class,
            SendToMqtt::class
        ];
    }

    /**
     * @param object $event
     * @throws \Exception
     */
    public function process(object $event): void
    {

        DebugHelper::consoleWrite('异步任务监听-process', [
            'event' => $event
        ]);
        if ($event instanceof Notify) {
            DebugHelper::consoleWrite('event-Notify');
        } elseif ($event instanceof SendToWebSocket) {
            DebugHelper::consoleWrite('异步任务监听-SendToWebSocket', $event->data);
            $this->sender->push($event->fd, $event->data);
        } elseif ($event instanceof SendToTcp) {
            DebugHelper::consoleWrite('异步任务监听-SendToTcp', $event->data);

            DebugHelper::consoleWrite('event-SendToTcp');
            $client = new \Swoole\Client(SWOOLE_SOCK_TCP);
            $client->connect($event->ip, $event->port);
            $client->send($event->data);
        } elseif ($event instanceof SendToMqtt) {
            DebugHelper::consoleWrite('异步任务监听-SendToMqtt', [
                $event->topic,
                $event->message,
                $event->qos,
                $event->dup,
                $event->retain,
            ]);
            $MqttUtility = new MqttUtility();
            $client = $MqttUtility->getClient();
            $response = $client->publish(
                $event->topic,
                $event->message,
                $event->qos,
                $event->dup,
                $event->retain,
                [
                    'topic_alias' => 1,
                    'message_expiry_interval' => 12,
                ]
            );
            DebugHelper::consoleWrite('异步任务监听-SendToMqtt', [
                'response' => $response
            ]);
        }
        // 事件触发后该监听器要执行的代码写在这里，比如该示例下的发送用户注册成功短信等
        // 直接访问 $event 的 user 属性获得事件触发时传递的参数值
        // $event->user;
    }
}
